package com.example.drink_order_system.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.example.drink_order_system.R;
import com.example.drink_order_system.tool.ImageUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import DataBase.UserDbHelper;

public class User_manage extends AppCompatActivity {
    public static final int REQUEST_CODE_TAKE = 1;
    public static final int REQUEST_CODE_CHOOSE = 2;
    private ImageButton back;
    private ImageView change_head;
    private AppCompatButton confirm_change;
    private EditText change_name;
    private EditText change_password;
    private EditText confirm_password;
    private Uri imageUri;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_manage_layout);
        back = findViewById(R.id.user_back);
        change_head = findViewById(R.id.change_head);
        confirm_change = findViewById(R.id.confirm_change);
        change_name = findViewById(R.id.change_name_context);
        change_password = findViewById(R.id.change_password_context);
        confirm_password = findViewById(R.id.confirm_password_context);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        confirm_change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                change_head.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(change_head.getDrawingCache());
                change_head.setDrawingCacheEnabled(false);
                String new_userImg = ImageUtil.imageToBase64(bitmap);
                if (change_name.getText().toString().equals("")||change_password.getText().toString().equals("")){
                    Toast.makeText(getApplication(),"信息不能为空！",Toast.LENGTH_SHORT).show();
                }else if (change_password.getText().toString().equals(confirm_password.getText().toString())){
                    String username = change_name.getText().toString();
                    String password = change_password.getText().toString();
                    UserDbHelper db = (UserDbHelper) UserDbHelper.getSqliteHelper(getApplication());
                    db.change_info(MainActivity.now_user.getUsername(),username,password,new_userImg);
                    RootActivity.getIns().finish();
                    finish();
                    Toast.makeText(getApplication(),"修改成功！请重新登录！",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplication(),"密码不一致！",Toast.LENGTH_SHORT).show();
                }
            }
        });

        change_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(User_manage.this)
                        .setTitle("更改头像")
                        .setMessage("请选择更改方式")
                        .setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if(ContextCompat.checkSelfPermission(User_manage.this, android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
                                    //去拍照
                                    doTake();
                                }else{
//                                    Toast.makeText(getActivity(),"权限申请失败，正在重新申请",Toast.LENGTH_SHORT).show();
                                    //去申请权限
                                    ActivityCompat.requestPermissions(User_manage.this,new String[]{Manifest.permission.CAMERA},1);
                                }
                            }
                        })
                        .setNegativeButton("从相册中选择", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                /*打开图库*/
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                //处理返回集
                                startActivityForResult(intent, 2);
                            }
                        }).show();
            }
        });


    }

    private void doTake() {
        File imageTemp = new File(getExternalCacheDir(),"imageOut.jpeg");
        if(imageTemp.exists()){
            imageTemp.delete();
        }
        try {
            imageTemp.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }

        if(Build.VERSION.SDK_INT>24){
            imageUri = FileProvider.getUriForFile(User_manage.this,"com.example.drink_order_system.fileprovider",imageTemp);
        }else{
            imageUri = Uri.fromFile(imageTemp);
        }
        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,REQUEST_CODE_TAKE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 1){
            if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                doTake();
            }else {
                Toast.makeText(User_manage.this, "你没有获得摄像头的权限", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode==2) {
            if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                Log.d("-----------------","正在打开相册");
                openAlbum();
            }else {
                Toast.makeText(User_manage.this, "你没有获得访问相册的权限", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void openAlbum() {
        Toast.makeText(User_manage.this,"正在打开相册",Toast.LENGTH_SHORT).show();

        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,REQUEST_CODE_CHOOSE);
    }
    @SuppressLint("Range")
    @Override
    public void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_TAKE){
            if(resultCode == RESULT_OK){//存疑
                // 获取拍摄照片
                InputStream inputStream = null;
                try {
                    inputStream = getContentResolver().openInputStream(imageUri);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);//用于保存头像
//            user_img.setImageBitmap(bitmap);

                Glide.with(this).load(bitmap).circleCrop().into(change_head);
            }
            //之后用数据库和ImageUtil转成String保存在用户表中


        } else if (requestCode == 2) {//从相册中获取
            Uri path = data.getData();
            //利用框架加载图片资源
            Glide.with(this).load(path).centerCrop().into(change_head);

            Bitmap bitmap = BitmapFactory.decodeFile(path.getPath());//用于保存头像
//            if(Build.VERSION.SDK_INT<19){
//                handleImageBeforeApi19(data);
//            }else{
//                handleImageOnApi19(data);
//            }

        }
    }
    private void handleImageBeforeApi19(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }


    private void handleImageOnApi19(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if(DocumentsContract.isDocumentUri(User_manage.this,uri)){
            String documentId = DocumentsContract.getTreeDocumentId(uri);
            if(TextUtils.equals(uri.getAuthority(),"com.android.providers.media.document")){
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+"="+id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            } else if (TextUtils.equals(uri.getAuthority(),"com.android.providers.downloads.documents")) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        }else{
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imgPath){
        if(imgPath!=null){
            Uri uri = Uri.parse(imgPath);
//            Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
//            user_img.setImageBitmap(bitmap);
            Glide.with(this).load(uri).circleCrop().into(change_head);
            //之后用数据库和ImageUtil转成String保存在用户表中
        }
    }

}
